package com.iot.service.mqtt.handler;

import com.iot.service.mqtt.config.Constant;
import com.iot.service.mqtt.model.request.TlMqttPubAckReq;
import com.iot.service.mqtt.model.variable.TlMqttPubAckVariableHead;
import com.iot.service.mqtt.retry.RetryStrategy;
import com.iot.service.mqtt.service.pub.IPublishStoreService;
import com.iot.service.mqtt.service.session.ISessionService;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.util.AttributeKey;
import lombok.RequiredArgsConstructor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

/**
 * @ClassName：ConnectHandler
 * @Author: hszhou
 * @Date: 2024/11/25 11:06
 * @Description: 必须描述类做什么事情, 实现什么功能
 */
@ChannelHandler.Sharable
@Component
@RequiredArgsConstructor
public class TlMqttPubAckHandler extends SimpleChannelInboundHandler<TlMqttPubAckReq> {

    private static final  Logger logger = LoggerFactory.getLogger(TlMqttPubAckHandler.class);


    private final ISessionService sessionService;

    private final IPublishStoreService publishStoreService;

    private final RetryStrategy retryStrategy;

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, TlMqttPubAckReq msg) throws Exception {

        logger.debug("in【PUBACK】 handler");
        Object clientId = ctx.channel().attr(AttributeKey.valueOf(Constant.CLIENT_ID)).get();
        if(clientId==null){
            ctx.channel().close();
            return;
        }
        String clientIdStr = clientId.toString();

        TlMqttPubAckVariableHead variableHead = msg.getVariableHead();
        Long messageId = variableHead.getMessageId();
        logger.debug("receive client 【{}】 messageId 【{}】 ack",clientId,messageId);
        //删除本地存储的消息
        publishStoreService.clearPublishMessage(clientIdStr,messageId).subscribe(
                //取消重发逻辑
                e-> {
                    retryStrategy.cancel(messageId);
                }
        );
    }
}
